/*
This file is part of buco.  
Copyright (c) 2012 Christopher Pawelzik <christopher@cpawelzik.com>

Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
*/ 

function BundleCompositionView(composition) { 
	this.composition = composition; 	
}

BundleCompositionView.prototype.show = function(target) { 		
	// clear composition container
	target.empty(); 

	if(this.composition.bundles == null || this.composition.bundles.length == 0) 
		return; 					

	for(var i=0; i < this.composition.bundles.length; i++) {
		var bundle = this.composition.bundles[i]; 
		var name = bundle.bundleSymbolicName;
		var id = "bundle" + bundle.bundleID;
					
		target.append("<div class=\"component\" id=\"" + 
			id + "\">" + 
			name + 
			"</div>"); 
		
		if(bundle.top != null) 
			$("#" + id).css("top", bundle.top + "px");
		if(bundle.left != null) 
			$("#" + id).css("left", bundle.left + "px");
	}

	// Make components selectable 
	if($(".component") != null) { 
		$(".component").click(function(evt) {
			$(".component").removeClass("componentSel"); 
			$(this).addClass("componentSel"); 
			var id = $(this).attr("id");
			id = id.replace("bundle", ""); 							
			buco.mvc.executeAction("composition.selectBundle", id);  			
		}); 
	}

	jsPlumb.draggable($(".component"), 
		{stop: function(event, ui) {					
			// Notify position change					
			var id = $(this).attr("id");
			id = id.replace("bundle", ""); 					
			var params = {
				top: ui.position.top, 
				left: ui.position.left, 
				bundleID: parseInt(id)
			};					
			buco.rpc.setBundlePosition({params: params}); 
		}
	});				
				
	jsPlumb.importDefaults({
	Endpoint : ["Dot", {radius:2}],
	HoverPaintStyle : {strokeStyle:"#42a62c", lineWidth:2 },
	ConnectionOverlays : [
		[ "Arrow", { 
			location:1,
			id:"arrow",
			length:8,
			width: 10,
			foldback:0.7
		} ],		
	]
	});

	// Connect bundles 
	for(var i=0; i < this.composition.wires.length; i++) {
		var from = "bundle" + this.composition.wires[i].from; 
		var to = "bundle" + this.composition.wires[i].to; 				
		var color = this.composition.wires[i].isActive ? "black" : "#D8D8D8"; 
						
		var wire = jsPlumb.connect({
			source: from,
			target: to, 
			anchor:"AutoDefault", 
			endpoint:[ "Dot", { radius:2}],
			connector:[ "StateMachine", { curviness:20 } ],
			connectorStyle:{ lineWidth:2 },
			paintStyle:{ strokeStyle:color, lineWidth:2 }
		});			

		wire.bind("click", function(conn) { 							
			buco.mvc.executeAction("composition.showWire", conn);			
		});
	}
}
